// 表格操作功能模块
const tableFunctions = {
    mergeCells() {
        const table = document.getElementById('myTable');
        if (tableSelection.selectedCells.length < 2) return;

        tableState.saveState(table);

        let minRow = Infinity, maxRow = -1;
        let minCol = Infinity, maxCol = -1;
        
        tableSelection.selectedCells.forEach(cell => {
            const row = cell.parentElement.rowIndex;
            const col = tableSelection.getCellStartColumn(cell);
            minRow = Math.min(minRow, row);
            maxRow = Math.max(maxRow, row + (cell.rowSpan || 1) - 1);
            minCol = Math.min(minCol, col);
            maxCol = Math.max(maxCol, col + (cell.colSpan || 1) - 1);
        });

        let coveredArea = new Set();
        tableSelection.selectedCells.forEach(cell => {
            const startRow = cell.parentElement.rowIndex;
            const startCol = tableSelection.getCellStartColumn(cell);
            const rowSpan = cell.rowSpan || 1;
            const colSpan = cell.colSpan || 1;

            for (let i = 0; i < rowSpan; i++) {
                for (let j = 0; j < colSpan; j++) {
                    coveredArea.add(`${startRow + i},${startCol + j}`);
                }
            }
        });

        const expectedArea = (maxRow - minRow + 1) * (maxCol - minCol + 1);
        if (coveredArea.size !== expectedArea) {
            alert('请选择矩形区域进行合并！');
            tableSelection.clearSelection();
            return;
        }

        const firstCell = table.rows[minRow].cells[tableSelection.getCellStartColumn(tableSelection.selectedCells[0])];
        const content = tableSelection.selectedCells.map(cell => cell.textContent.trim()).join(' ');
        firstCell.textContent = content;
        firstCell.rowSpan = maxRow - minRow + 1;
        firstCell.colSpan = maxCol - minCol + 1;

        tableSelection.selectedCells.forEach(cell => {
            if (cell !== firstCell) {
                cell.remove();
            }
        });

        tableSelection.clearSelection();
    },

    splitCell() {
        const table = document.getElementById('myTable');
        if (tableSelection.selectedCells.length !== 1) {
            alert('请选择一个已合并的单元格进行拆分！');
            tableSelection.clearSelection();
            return;
        }

        const cell = tableSelection.selectedCells[0];
        const rowSpan = cell.rowSpan || 1;
        const colSpan = cell.colSpan || 1;

        if (rowSpan === 1 && colSpan === 1) {
            alert('该单元格未合并，无需拆分！');
            tableSelection.clearSelection();
            return;
        }

        tableState.saveState(table);

        const row = cell.parentElement;
        const rowIndex = row.rowIndex;
        const cellContent = cell.textContent;

        cell.rowSpan = 1;
        cell.colSpan = 1;
        cell.textContent = cellContent;

        for (let j = 1; j < colSpan; j++) {
            const newCell = row.insertCell(cell.cellIndex + j);
            newCell.textContent = '';
        }

        for (let i = 1; i < rowSpan; i++) {
            const nextRow = table.rows[rowIndex + i];
            const refCell = nextRow.cells[cell.cellIndex];
            
            for (let j = 0; j < colSpan; j++) {
                const newCell = nextRow.insertCell(
                    refCell ? refCell.cellIndex : nextRow.cells.length
                );
                newCell.textContent = '';
            }
        }

        tableSelection.clearSelection();
    },

    insertColumnRight() {
        const table = document.getElementById('myTable');
        if (tableSelection.selectedCells.length !== 1) return;

        tableState.saveState(table);
        
        const selectedCell = tableSelection.selectedCells[0];
        // 计算选中单元格的实际结束列位置
        const selectedCellStartCol = tableSelection.getCellStartColumn(selectedCell);
        const selectedCellEndCol = selectedCellStartCol + (selectedCell.colSpan || 1) - 1;
        // 找到选中单元格的下1个单元格，并在该位置插入，从而实现插入列总是选中行的右侧
        // +1选中单元格的后面插入
        const insertColIndex = selectedCellEndCol + 1;

        // 遍历所有行插入新列
        for (let i = 0; i < table.rows.length; i++) {
            const row = table.rows[i];
            let currentCol = 0;
            let inserted = false;
            
            // 遍历当前行的所有单元格
            for (let j = 0; j < row.cells.length && !inserted; j++) {
                const cell = row.cells[j];
                const colSpan = cell.colSpan || 1;
                const cellStartCol = tableSelection.getCellStartColumn(cell);
                const cellEndCol = cellStartCol + colSpan - 1;
                // 如果找到了插入位置
                if (cellStartCol === insertColIndex) {
                    // 找到了选中后的单元格，并在该位置进行插入列
                    // j是真实DOM中的位置
                    const newCell = row.insertCell(j);
                    newCell.textContent = '';
                    inserted = true;
                    break;
                }

                // 如果当前单元格跨越了插入位置
                // 如果要插入的insertColIndex在列合并的单元格之间
                if (cellStartCol <= insertColIndex && cellEndCol >= insertColIndex) {
                    cell.colSpan = colSpan + 1;
                    inserted = true;
                    break;
                }
                
                currentCol += colSpan;
            }
            
            // 如果需要在行尾插入
            if (!inserted && currentCol <= insertColIndex) {
                const newCell = row.insertCell();
                newCell.textContent = '';
            }
        }
        
        tableSelection.clearSelection();
    },

    insertRowBelow() {
        const table = document.getElementById('myTable');
        if (tableSelection.selectedCells.length !== 1) return;

        tableState.saveState(table);
        
        const selectedCell = tableSelection.selectedCells[0];
        const rowIndex = selectedCell.parentElement.rowIndex + (selectedCell.rowSpan || 1) - 1;
        const newRow = table.insertRow(rowIndex + 1);
        debugger
        // 获取表格的最大列数
        const maxCols = tableData.getMaxCols(tableData.getTableData(table));
        let currentCol = 0;
        
        // 遍历上一行的所有单元格
        let cellIndex = 0;
        while (currentCol < maxCols) {
            let handled = false;
            
            // 检查上一行的单元格
            if (cellIndex < table.rows[rowIndex].cells.length) {
                const cell = table.rows[rowIndex].cells[cellIndex];
                const colSpan = cell.colSpan || 1;
                
                // 如果单元格向下合并且跨越插入位置
                if (cell.rowSpan && cell.rowSpan > 1 && 
                    cell.parentElement.rowIndex + cell.rowSpan - 1 > rowIndex) {
                    cell.rowSpan += 1;
                    currentCol += colSpan;
                    handled = true;
                }
                
                cellIndex++;
            }
            
            // 如果该位置没有被合并单元格占据，插入新单元格
            if (!handled) {
                // 检查上方是否有跨行单元格
                const parentCell = this.findParentCell(table, rowIndex + 1, currentCol);
                if (parentCell && parentCell.rowSpan > rowIndex + 1 - parentCell.parentElement.rowIndex) {
                    // 如果有跨行单元格，增加其rowSpan
                    parentCell.rowSpan += 1;
                    currentCol += (parentCell.colSpan || 1);
                } else {
                    // 否则插入新单元格
                    const newCell = newRow.insertCell();
                    newCell.textContent = '';
                    
                    // 检查上一行对应位置的单元格是否有colspan
                    const aboveCell = this.findCellAtColumn(table.rows[rowIndex], currentCol);
                    if (aboveCell && aboveCell.colSpan > 1) {
                        newCell.colSpan = aboveCell.colSpan;
                        currentCol += aboveCell.colSpan;
                    } else {
                        currentCol += 1;
                    }
                }
            }
        }
        
        tableSelection.clearSelection();
    },

    // 辅助方法：在指定行中找到覆盖指定列的单元格
    findCellAtColumn(row, targetCol) {
        let currentCol = 0;
        for (let i = 0; i < row.cells.length; i++) {
            const cell = row.cells[i];
            const colSpan = cell.colSpan || 1;
            if (currentCol <= targetCol && currentCol + colSpan > targetCol) {
                return cell;
            }
            currentCol += colSpan;
        }
        return null;
    },

    removeColumn() {
        const table = document.getElementById('myTable');
        if (tableSelection.selectedCells.length !== 1) return;

        tableState.saveState(table);
        
        const selectedCell = tableSelection.selectedCells[0];
        const removeColIndex = tableSelection.getCellStartColumn(selectedCell);
        
        // 遍历所有行删除列
        for (let i = 0; i < table.rows.length; i++) {
            const row = table.rows[i];
            let currentCol = 0;
            let handled = false;
            
            for (let j = 0; j < row.cells.length && !handled; j++) {
                const cell = row.cells[j];
                const colSpan = cell.colSpan || 1;
                const cellStartCol = currentCol;
                
                // 如果单元格正好在要删除的位置
                if (cellStartCol === removeColIndex && colSpan === 1) {
                    cell.remove();
                    handled = true;
                }
                // 如果是跨列单元格且包含要删除的列
                else if (cellStartCol <= removeColIndex && 
                    cellStartCol + colSpan > removeColIndex) {
                    cell.colSpan = colSpan - 1;
                    handled = true;
                }
                
                currentCol += colSpan;
            }
        }
        
        tableSelection.clearSelection();
    },

    removeRow() {
        const table = document.getElementById('myTable');
        if (tableSelection.selectedCells.length !== 1) return;

        tableState.saveState(table);
        
        const selectedCell = tableSelection.selectedCells[0];
        const removeRowIndex = selectedCell.parentElement.rowIndex;
        
        // 检查并调整跨行单元格
        for (let i = 0; i < table.rows[removeRowIndex].cells.length; i++) {
            const cell = table.rows[removeRowIndex].cells[i];
            const startRowIndex = cell.parentElement.rowIndex;
            
            // 如果是从上一行延伸下来的跨行单元格
            if (startRowIndex < removeRowIndex) {
                const parentCell = this.findParentCell(table, removeRowIndex, i);
                if (parentCell && parentCell.rowSpan > 1) {
                    parentCell.rowSpan--;
                }
                continue;
            }
            
            // 如果当前单元格向下跨行
            if (cell.rowSpan > 1) {
                // 将单元格复制到下一行
                const nextRow = table.rows[removeRowIndex + 1];
                const newCell = nextRow.insertCell(i);
                newCell.textContent = cell.textContent;
                newCell.rowSpan = cell.rowSpan - 1;
                newCell.colSpan = cell.colSpan || 1;
            }
        }
        
        // 删除行
        table.deleteRow(removeRowIndex);
        
        tableSelection.clearSelection();
    },

    // 辅助方法：查找跨行单元格的父单元格
    findParentCell(table, rowIndex, colIndex) {
        let currentCol = 0;
        // 向上查找包含当前位置的单元格
        for (let i = rowIndex - 1; i >= 0; i--) {
            const row = table.rows[i];
            currentCol = 0;
            
            for (let j = 0; j < row.cells.length; j++) {
                const cell = row.cells[j];
                const colSpan = cell.colSpan || 1;
                const rowSpan = cell.rowSpan || 1;
                
                if (currentCol <= colIndex && 
                    currentCol + colSpan > colIndex && 
                    i + rowSpan > rowIndex) {
                    return cell;
                }
                
                currentCol += colSpan;
            }
        }
        return null;
    }
}; 